import { ref, watch } from 'vue'
import { getUserGuideStorageBase, setUserGuideStorageBase } from '@src/util/guideStorage'

// 多列表单的引导弹窗标识
export const formWithMultipleColumnsStashKey = 'formWithMultipleColumns'


// 首页的自定义引导方法
export const useSataeFrameGuide = () => {
    const nowGuide: any = ref(null)
    const guideWaitList = ref([])
    const guideWaitActiveList = ref([formWithMultipleColumnsStashKey])
    const guideWaitActiveListStash:any = ref([])
    let initStoreNow = false

    function changeNowGuide(newVal: any) {
        nowGuide.value = newVal
    }

    async function initAllNowGuide() {
        initStoreNow = true
        try {
            let userGuide = await getUserGuideStorageBase()
            guideWaitActiveList.value = guideWaitActiveList.value.filter(i => {
                if (Reflect.has(userGuide, i)) {
                    return false
                }
                return true
            })
        } catch (error) {
            console.error(error, 'initAllNowGuide is Error')
        }
        initStoreNow = false
        if(guideWaitActiveListStash.value.length){
            activeGuide(guideWaitActiveListStash.value[0], true)
        }
    }

    function activeGuide(key: any, ignoreStash: boolean = false) {
        if(guideWaitActiveList.value.includes(key) && !ignoreStash){
            guideWaitActiveListStash.value.push(key)
        }
        if(initStoreNow){
            return 
        }
        if (nowGuide.value !== key && guideWaitActiveList.value.includes(key)) {
            changeNowGuide(key)
            setUserGuideStorageBase({
                userGuideList: [
                    {
                        type: key,
                        step: 1,
                        isComplete: 1
                    }
                ]
            })
        }
        guideWaitActiveListStash.value = guideWaitActiveListStash.value.filter(i=>i!==key)
        
    }
    function reActiveGuide(key: any) {
        if (guideWaitActiveList.value.includes(key)) {
            guideWaitActiveList.value = guideWaitActiveList.value.filter(i => i !== key)
        }
        if (nowGuide.value === key) {
            nowGuide.value = null
            if(guideWaitActiveListStash.value.length){
                activeGuide(guideWaitActiveListStash.value[0], true)
            }
        }
    }

    initAllNowGuide()

    return {
        activeGuide,
        nowGuide,
        reActiveGuide,
    }
}